import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
import Article from '@/views/article'

// 导入二级路由的相关组件
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import Search from '@/views/search'
import SearchResult from '@/views/search/searchResult'
import UserEdit from '@/views/layout/user/edit'

// 导入 vuex 的store
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '',
    component: Layout,
    // 重定向
    // redirect: '/home',
    children: [
      { path: '', component: Home, meta: { isKeepAlive: true } },
      { path: '/qa', component: Qa },
      { path: '/video', component: Video },
      { path: '/user', component: User }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  { path: '/search', component: Search },
  { path: '/search/result', component: SearchResult },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '*',
    compponent: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 注册全局的导航守卫
// 每一次的跳转都会触发导航守卫
// 需要登录才可以访问的
const loginURLs = ['/user']

router.beforeEach((to, from, next) => {
  // console.log('从哪里来', from)
  // console.log('到哪里去', to)
  next() // next 是个函数 需要调用,不然无法跳转进入需要的页面

  const token = store.state.user.token.token
  // console.log(token)

  // 判断
  if (token) {
    // 有token 放行
    next()
  } else {
    // 没有token
    // 继续判断
    if (loginURLs.some(item => item === to.path)) {
      router.push({
        path: '/login',
        query: {
          back: to.fullPath // 本来要去的页面
        }
      })
    } else {
      // 不需要登录
      next()
    }
  }
})

export default router
